<?php

namespace Celebrio\FileSystem\Drivers;

use Nette\Object;
use \DibiFluent;
use \dibi;

use Celebrio\FileSystem\GenericFile;
use Celebrio\FileSystem\DataFile;
use Celebrio\FileSystem\VirtualFile;
use \InvalidArgumentException;

use Celebrio\Diagnostics\Timer;
use Celebrio\Diagnostics\TimerLevel;


class AzureCelebrioDatabase extends Object {
    
    
    
    public function getOwnerId(DataFile $dataFile) {
        Timer::start("AzureDriverDB - getOwner", TimerLevel::OVERVIEW);
        $name = $dataFile->getName();
        $url = VirtualFile::VIRTUAL_ROOT . $dataFile->getUrl();
        
        $owner = dibi::query("SELECT [id] FROM [users] JOIN [files]
            ON [id] = [id_user] WHERE name_file=%s AND url=%s", $name, $url)->fetch();
        
        Timer::stop("AzureDriverDB - getOwner");
        return $owner["id"];
        
    }
    
    /**
     * 
     * 
     * @param DataFile $dataFile
     * @param bool $id when is true, function returns name and id insted of name.
     * @return string $result name 
     */
    public function getOrMakeRemoteName(DataFile $dataFile) {
        Timer::start("AzureDriverDB - getRemoteName", TimerLevel::OVERVIEW);
        $name = $dataFile->getName();
        $url = "root" . $dataFile->getUrl();
        $azureName = dibi::fetchSingle("SELECT [name_azure_file] 
            FROM [azure_files] JOIN [files]
            ON [azure_files.id_file] = [files.id_file] 
            WHERE name_file=%s AND url=%s", $name, $url);
        
        if(!$azureName) {
            $id = $this->getFileId($dataFile);
            $azureName = \sha1($id . $url . $name);
            
            $args = array(
                "id_file" => $id,
                "name_azure_file" => $azureName
            );
            dibi::query("INSERT INTO [azure_files]", $args);
        }
        Timer::stop("AzureDriverDB - getRemoteName");
        return $azureName;
    }
    
    private function getFileId(DataFile $dataFile) {
        Timer::start("AzureDriverDB - getID", TimerLevel::OVERVIEW);
        $result = dibi::select("id_file")
                        ->from("files")
                        ->where("name_file=%s and url=%s", 
                                $dataFile->getName(), 
                                "root" . $dataFile->getUrl())
                        ->fetchSingle();
        
        
        Timer::stop("AzureDriverDB - getID");
        if(!$result) {
            throw new InvalidArgumentException("This file does not exist");
        } else {
            return $result;
        }
    }
}
